const app = getApp();

Page({
  data: {
    avatar: '/images/avatar/default.png',
    nickname: '',
    gender: '',
    birth_year: '',
    income: '',
    incomeIndex: 0,
    incomeOptions: ['3000以下', '3000-5000', '5000-8000', '8000-12000', '12000-20000', '20000以上'],
    city: '',
    region: [],
    province: '',
    district: '',
    dating_type: '',
    interestOptions: [
      { label: '跳舞', value: '跳舞', active: false },
      { label: '音乐', value: '音乐', active: false },
      { label: '棋牌麻将', value: '棋牌麻将', active: false },
      { label: '其他', value: '其他', active: false }
    ],
    selectedInterests: [],
    featuredPhotos: [],
    description: '',
    saving: false
  },

  onLoad() {
    this.loadUserProfile();
  },

  // 加载用户资料
  loadUserProfile() {
    const userProfile = app.globalData.userProfile;
    if (userProfile) {
      this.setData({
        avatar: userProfile.avatar || '/images/avatar/default.png',
        nickname: userProfile.nickname || '',
        gender: userProfile.gender || '',
        birth_year: userProfile.birth_year || '',
        income: userProfile.income || '',
        city: userProfile.city || '',
        dating_type: userProfile.dating_type || '',
        description: userProfile.description || '',
        featuredPhotos: Array.isArray(userProfile.featuredPhotos) ? userProfile.featuredPhotos : []
      });

      // 设置收入索引
      const incomeIndex = this.data.incomeOptions.findIndex(item => item === userProfile.income);
      if (incomeIndex > -1) {
        this.setData({
          incomeIndex: incomeIndex
        });
      }

      // 设置地区（若已保存）
      if (userProfile.province && userProfile.city) {
        this.setData({
          province: userProfile.province,
          city: userProfile.city,
          district: userProfile.district || '',
          region: [userProfile.province, userProfile.city, userProfile.district || '']
        });
      }

      // 兴趣（若已保存）
      if (Array.isArray(userProfile.interests)) {
        const selected = userProfile.interests;
        const opts = this.data.interestOptions.map(opt => ({ ...opt, active: selected.includes(opt.value) }));
        this.setData({ selectedInterests: selected, interestOptions: opts });
      }
    }
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          avatar: res.tempFilePaths[0]
        });
      }
    });
  },

  // 昵称输入
  onNicknameInput(e) {
    this.setData({
      nickname: e.detail.value
    });
  },

  // 选择性别
  selectGender(e) {
    const gender = e.currentTarget.dataset.gender;
    this.setData({
      gender: gender
    });
  },

  // 选择出生年份
  onBirthYearChange(e) {
    this.setData({
      birth_year: e.detail.value
    });
  },

  // 选择收入
  onIncomeChange(e) {
    const index = e.detail.value;
    this.setData({
      incomeIndex: index,
      income: this.data.incomeOptions[index]
    });
  },

  // 城市输入
  onCityInput(e) {
    this.setData({
      city: e.detail.value
    });
  },

  // 选择地区
  onRegionChange(e) {
    const value = e.detail.value || [];
    this.setData({
      region: value,
      province: value[0] || '',
      city: value[1] || '',
      district: value[2] || ''
    });
  },

  // 选择交友类型
  selectDatingType(e) {
    const type = e.currentTarget.dataset.type;
    const updates = { dating_type: type };
    if (type !== 'friend') {
      updates.selectedInterests = [];
      updates.interestOptions = this.data.interestOptions.map(opt => ({ ...opt, active: false }));
    }
    this.setData(updates);
  },

  // 切换兴趣多选
  toggleInterest(e) {
    const index = e.currentTarget.dataset.index;
    const options = this.data.interestOptions.slice();
    const target = options[index];
    if (!target) return;
    target.active = !target.active;
    const selected = options.filter(o => o.active).map(o => o.value);
    this.setData({ interestOptions: options, selectedInterests: selected });
  },

  // 精选照片上传
  addFeaturedPhotos() {
    const remain = 10 - this.data.featuredPhotos.length;
    if (remain <= 0) return;
    wx.chooseImage({
      count: remain,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const files = res.tempFilePaths || [];
        this.setData({ featuredPhotos: this.data.featuredPhotos.concat(files).slice(0, 10) });
      }
    });
  },

  // 精选照片删除
  removeFeaturedPhoto(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.featuredPhotos.slice();
    list.splice(index, 1);
    this.setData({ featuredPhotos: list });
  },

  // 交友说明输入
  onDescriptionInput(e) {
    this.setData({
      description: e.detail.value
    });
  },

  // 保存资料
  saveProfile() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({
      saving: true
    });

    const profile = {
        avatar: this.data.avatar,
        nickname: this.data.nickname,
        gender: this.data.gender,
        birth_year: parseInt(this.data.birth_year),
        age: new Date().getFullYear() - parseInt(this.data.birth_year),
        income: this.data.income,
        province: this.data.province,
        city: this.data.city,
        district: this.data.district,
        region: this.data.region,
        dating_type: this.data.dating_type,
        interests: this.data.selectedInterests,
        photos: this.data.featuredPhotos,
        description: this.data.description
      };

    wx.request({
        url: app.globalData.baseUrl + 'api/user-profile',
        method: 'POST',
        header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        data: profile,
        success: res => {
            if (res.data.code === 0) {
                // 更新全局数据
                app.globalData.userProfile = profile;
                if (app.globalData.userInfo) {
                    app.globalData.userInfo.profile = profile;
                    wx.setStorageSync('userInfo', app.globalData.userInfo);
                }

                this.setData({
                    saving: false
                });

                wx.showToast({
                    title: '保存成功',
                    icon: 'success'
                });

                // 返回上一页
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        },
        fail: () => {
            wx.showToast({
                title: "保存失败",
                icon: 'none'
            })
        },
        complete: () => {
            this.setData({
                saving: false
            });
        }
    })

  },

  // 验证表单
  validateForm() {
    if (!this.data.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.birth_year) {
      wx.showToast({
        title: '请选择出生年份',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.income) {
      wx.showToast({
        title: '请选择月收入',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.region || this.data.region.length !== 3) {
      wx.showToast({
        title: '请选择省市区',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.dating_type) {
      wx.showToast({
        title: '请选择交友类型',
        icon: 'none'
      });
      return false;
    }

    if (this.data.dating_type === 'friend' && this.data.selectedInterests.length === 0) {
      wx.showToast({
        title: '请选择兴趣方向',
        icon: 'none'
      });
      return false;
    }

    return true;
  }
}); 